package com.itheima.intercepter;

import com.itheima.utlis.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginCheckIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求url
        String url = request.getRequestURI();
        log.info("拦截的请求路径是：{}",url);
        //判断url是否包括login，如果包含说明是登录，则放行
        if (url.contains("login")){
            return true;
        }
        //3.获取请求头中的令牌
        String token = request.getHeader("token");
        //4.判断令牌是否存在，不存在响应401
        if (token == null){
            log.info("请求头中不存在token");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            //不放行
            return false;
        }
        //5.解析token，如果解析失败响应401
        try {
            Claims claims = JwtUtils.parseJWT(token);
            log.info("当前用户："+claims);
        } catch (Exception e) {
            log.error("令牌解析失败{}",e.getMessage());
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            //不放行
            return false;
        }

        //6.放行

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
